package top.broncho.lottery.ui.ocr

import android.app.Activity
import android.os.Bundle
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import kotlinx.coroutines.launch
import org.jetbrains.anko.design.snackbar
import org.jetbrains.anko.info
import top.broncho.lottery.R
import top.broncho.lottery.databinding.ActivityOcrBinding
import top.broncho.lottery.databinding.LayoutSsqItemBinding
import top.broncho.lottery.ui.base.BaseDiActivity
import top.broncho.lottery.ui.image.requestImage
import top.broncho.lottery.util.FILE_NAME
import java.io.File

class OcrActivity : BaseDiActivity<OcrViewModule, ActivityOcrBinding>() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding?.vm = viewModule

        viewModule.ocrResult.observe(this, Observer { ocr ->
            if (ocr.throwable != null) {
                binding?.root?.snackbar(ocr.throwable.message.toString())
                return@Observer
            }
            info { "ocrResult: ${ocr.result}" }

            binding?.ocrResult = ocr.result
            ocr.result?.list?.forEach {
                val itemBinding = DataBindingUtil.inflate<LayoutSsqItemBinding>(
                    layoutInflater,
                    R.layout.layout_ssq_item,
                    null,
                    false
                ).apply {
                    list = it
                }
                binding?.currentContainer?.addView(itemBinding.root)
            }
        })
        viewModule.saveDataBaseState.observe(this, Observer {
            if (it.result!!) {
                setResult(Activity.RESULT_OK)
                finish()
            } else {
                binding?.root?.snackbar("存储失败，请重试")
            }
        })
        if (viewModule.ocrResult.value == null) {
            requestImage()
        }
    }

    private fun requestImage() = launch {
        val path = File(externalCacheDir.takeIf { it != null } ?: cacheDir,
            FILE_NAME).absolutePath
        val result = requestImage(path)
        info { "requestImage: $result" }
        if (!result) {
            binding?.root?.snackbar("获取彩票照片失败，请重试")
            return@launch
        }
        viewModule.recognizeAccurate(path)
    }

    override fun getLayoutId() = R.layout.activity_ocr

}
